/** @author seafors
 * @E-mail: seafors@hotmail.com
 * @version 1.0.0 
 * 创建时间：Aug 30, 2012 3:50:32 PM 
 * 闹钟计时器, 指定多少毫秒后, 执行什么动作
 * 
 * 
 * 		//***********使用方法示例*****************
		this.addEventListener("a", onA);
		clo = Clock.getInstance();
		var code:int;
		for (var i:int; i < 1000; i++){
			delay = Math.random() * 2000;
			clo.pushEvent(this, "a", delay, String(code));
		}
		private function onA(e:ClockEvent):void{
		}//close function
 **/
package com.common.utils{
	
	import com.event.CommenEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	public class Clock extends Timer{
		private static var newLock:Boolean;
		public static var instance:Clock;
		private var arrEvent:Array;
		public static const delay:int = 20;
		
		public function Clock(delay:Number, repeatCount:int=0){
			super(delay, repeatCount);
			if (newLock){
				init();
				addEventListener(TimerEvent.TIMER, onTimer);
			}else{
				throw new Error("Clock实例化遭遇重复实例化冲突");
			}
		}
		public static function getInstance():Clock{
			if (Clock.instance){
				return Clock.instance;
			}else{
				newLock = true;
				Clock.instance = new Clock(Clock.delay);
				newLock = false;
				return Clock.instance;
			}
		}//close function
		private function init():void{
			arrEvent = new Array();
			super.start();
		}//close function
		public function pushEvent(dispathcer:EventDispatcher, action:String, delay:uint, body:Object = null):void{
			var count:Number = currentCount + delay / Clock.delay;//转换成次数
			var o:Object = {dispatcher:dispathcer, action:action, count:count, body:body};
			var index:int, i:int;
			var len:int = arrEvent.length;
			for (i = 0; i < len; i++){
				if (arrEvent[i].count > count){
					index = i;
					i = len + 1;
				}
			}
			if (i > len){
				arrEvent.splice(index, 0, o);
			}else{
				arrEvent.push(o);
			}
		}
		private function onTimer(e:TimerEvent):void{
			var i:int = 0;
			var o:Object;
			if (arrEvent[0].count <= currentCount){
				while(i < arrEvent.length){
					if (i < arrEvent.length){
						if (arrEvent[i].count <= currentCount){
							o = arrEvent[i];
							(o.dispatcher as EventDispatcher).dispatchEvent(new CommenEvent(o.action, o.body));
							arrEvent.splice(i, 1);
							if (!arrEvent.length) stop();
						}else{
							i =  arrEvent.length;
						}
					}else{
						i = arrEvent.length;
					}
				}
			}
		}//close function
	}
}
